﻿using System;
using System.Linq;
using Unis.Framework.Core.Exceptions;
using Unis.Framework.Core.Utility;
using Unis.Framework.ORM.Mapping;
using Unis.ORM.Mapping;

namespace Unis.Framework.ORM.Persistence
{
    public class EntityDataHelper
    {
        // Fields
        private static EntityDataHelper _Instance;
        private static object _Obj = new object();

        // Methods
        protected EntityDataHelper()
        {
        }

        public object GetEntityKeyValue(object entity)
        {
            string keyPropertyName = string.Empty;
            return this.GetEntityKeyValue(entity, out keyPropertyName);
        }

        public object GetEntityKeyValue(object entity, out string keyPropertyName)
        {
            Type t = entity.GetType();
            ModelMappingInfo modelMappingInfo = AttMappingManager.Instance.GetModelMappingInfo(t);
            if (string.IsNullOrEmpty(modelMappingInfo.MapTable))
            {
                throw new APPException(string.Format("数据实体{0} 配置有误，没有指定映射到的表。", t.FullName), APPMessageType.SysErrInfo);
            }
            if ((modelMappingInfo.PrimaryKeys == null) || (modelMappingInfo.PrimaryKeys.Count != 1))
            {
                throw new APPException(string.Format("数据实体{0} 配置有误，没有指定主键或者不是单一主键配置。", t.FullName), APPMessageType.SysErrInfo);
            }
            FieldPropertyInfo info2 = modelMappingInfo.PrimaryKeys.Values.First<FieldPropertyInfo>();
            object obj2 = Reflection.GetObjectProperty(entity, info2.PropertyName);
            keyPropertyName = info2.PropertyName;
            return obj2;
        }

        // Properties
        public static EntityDataHelper Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (_Obj)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new EntityDataHelper();
                        }
                    }
                }
                return _Instance;
            }
        }
    }
}
